#!/use/bin/python
# coding=utf-8
# 早间开机 数据分析-健康作息-服务推送成功率15分钟/30分钟
import datetime
import pymysql

from dbutils.pooled_db import PooledDB


# proactive_service_conf 数据源
def getConfConnection():
    # 开发环境
    # pool = PooledDB(pymysql, 1, host='172.20.135.96', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_conf',
    #                port=3306)  # 1为连接池里的最少连接数
    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                db='proactive_service_conf', port=3307)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

# proactive_service_data 数据源
def getDataConnection():
    # 开发环境
    #pool = PooledDB(pymysql, 1, host='172.20.151.80', user='pushdb', passwd='SkYWOrTh$TcOs',
    #                db='proactive_service_data',port=3306)  # 1为连接池里的最少连接数

    # 测试环境
    pool = PooledDB(pymysql, 1, host='172.20.154.103', user='test_dmp', passwd='DghHC3lFM1KzT3ZJ',
                    db='proactive_service_data', port=3407)  # 1为连接池里的最少连接数
    # pool = PooledDB(pymysql,1,host='127.0.0.1',user='root',passwd='root',db='life_assistant_data',port=3306) # 5为连接池里的最少连接数
    conn = pool.connection()
    cur = conn.cursor()
    return conn, cur

#根据传入的SQL 返回执行SQL返回的数量
def selectNumBySql(sql,conf=2):
    if conf == 1:
        conn, cur = getConfConnection()
    else:
        conn, cur = getDataConnection()
    #print(sql)
    cur.execute(sql)
    numResult = cur.fetchone()
    num = 0
    if numResult is not None:
        num = numResult[0]
    return num


#根据月份 获取本月指定指标的 总和
#tableName 指定的报表
#columnName 指定的指标字段
#date 月份
def getSumNumByTableColumnNameAndDate(tableName,columnName,date):
    conn, cur = getDataConnection()
    selectNumSql = f"""
                     select sum({columnName}) from {tableName} t where 1=1   
                     """;
    if len(date) >0:
        selectNumSql = f"""{selectNumSql} and SUBSTR( t.ref_date, 1,7) = '{date}' and LENGTH(t.ref_date) = 10  """
    cur.execute(selectNumSql)
    #print(selectNumSql);
    numResult = cur.fetchone()
    num = 0
    if numResult!= None:
        num = numResult[0]
    if num is None:
        return 0
    return num

#计算百分比 保留两位小数  如:34.88%
# X为分子 Y为分母
def getRateByXY(X,Y):
    rate = 0
    if(X is None or Y is None):
        return rate
    if Y != 0:
        if X > Y:
            rate = 100
        else:
            rate = round(X / Y, 4) * 100
    return rate

# 记录 数据分析-健康作息-服务推送成功率15分钟/30分钟
def insertStartupRate(date):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_jkzx_push_rate 表是否已经存在当天 数据
        countNum = selectNumBySql(f"select count(1) num from analysis_jkzx_push_rate t where 1=1  and t.ref_date =  '{date}'")
        # 获取当日健康作息 弹窗数量
        msgDict = {'result': 1}
        pushNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` = 'hlTipShow' and  DATE_FORMAT(t.create_time, '%Y-%m-%d') = '{date}'  and JSON_EXTRACT(msg,'$.result') =1")
        # 获取所有健康作息 弹窗数量
        pushAllNum = selectNumBySql(
            f"select sum(new_num) from analysis_jkzx_push_rate t where 1=1 and LENGTH(t.ref_date) = 10  ")
        # 获取 当日 收到健康作息弹窗 15分钟内关机的设备量
        close15MinNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` = 'hl15mClose'  and  DATE_FORMAT(t.create_time, '%Y-%m-%d') = '{date}' ")
        # 获取 当日 收到健康作息弹窗 30分钟内关机的设备量
        close30MinNum = selectNumBySql(
            f"select count(DISTINCT(t.active_id)) from log_common_service_{yyMMddDate} t where t.`key` = 'hl30mClose'  and  DATE_FORMAT(t.create_time, '%Y-%m-%d') = '{date}' ")
        # 获取收到健康作息弹窗 15/30分钟关闭电视量及成功率
        success15MinRate = getRateByXY(close15MinNum,pushNum)
        success30MinRate = getRateByXY(close30MinNum,pushNum)
        #获取睡眠时长不足7小时的设备量
        #1.起床在第二天
        min7hourNum1 =  selectNumBySql("""
            select count(DISTINCT(ttt.active_id)) from (
            select tt.active_id ,unix_timestamp(STR_TO_DATE(concat('2022-07-28 ',tt.sleep_time),'%Y-%m-%d %H:%i:%s'))sleep_time_t ,tt.sleep_time,
            unix_timestamp(STR_TO_DATE(concat('2022-07-29 ',tt.wakeup_time),'%Y-%m-%d %H:%i:%s')) wakeup_time_t,tt.wakeup_time from (
            select t.active_id,ifnull(t.wakeup_time,t.prediction_wakeup_time) wakeup_time,ifnull(t.sleep_time,t.prediction_sleep_time) sleep_time  from  proactive_service_device t where 1=1) tt where   tt.sleep_time is not null and tt.wakeup_time is not null and tt.sleep_time !=''and
            tt.wakeup_time !='' and tt.wakeup_time <tt.sleep_time
            )  ttt where 1=1 and  (ttt.wakeup_time_t - ttt.sleep_time_t) <60*60*7
          """,1)
        #2.睡觉起床同一天
        min7hourNum2 = selectNumBySql("""
                    select count(DISTINCT(ttt.active_id)) from (
            select tt.active_id ,unix_timestamp(STR_TO_DATE(concat('2022-07-28 ',tt.sleep_time),'%Y-%m-%d %H:%i:%s'))sleep_time_t ,tt.sleep_time,
            unix_timestamp(STR_TO_DATE(concat('2022-07-28 ',tt.wakeup_time),'%Y-%m-%d %H:%i:%s')) wakeup_time_t,tt.wakeup_time from (
            select t.active_id,ifnull(t.wakeup_time,t.prediction_wakeup_time) wakeup_time,ifnull(t.sleep_time,t.prediction_sleep_time) sleep_time  from  proactive_service_device t where 1=1) tt where   tt.sleep_time is not null and tt.wakeup_time is not null and tt.sleep_time !=''and
            tt.wakeup_time !='' and tt.wakeup_time >tt.sleep_time
            )  ttt where 1=1 and  (ttt.wakeup_time_t - ttt.sleep_time_t) <60*60*7
                  """,1)
        min7hourNum = min7hourNum1 + min7hourNum2
        if countNum == 0:
            logDetail = f"{date}日新增-睡眠时长不足7小时的设备量为{min7hourNum},健康作息弹窗数量为{pushNum},总量为{pushAllNum},15分钟内关闭数为{close15MinNum},15分钟内关机成功率为{success15MinRate},30分钟内关闭数为{close30MinNum},30分钟内关机成功率为{success30MinRate}"
            print(logDetail)
            # 插入早间服务可见设备量
            insertSql = f"""insert into analysis_jkzx_push_rate(min_7hour_num,new_num,cumulate_num,close_15min_num,close_30min_num
            ,success_15min_rate,success_30min_rate,ref_date) 
                value({min7hourNum},{pushNum},{pushAllNum},{close15MinNum},{close30MinNum},{success15MinRate},{success30MinRate},'{date}')"""
            cur.execute(insertSql)
        else:
            logDetail = f"{date}日更新-睡眠时长不足7小时的设备量为{min7hourNum},健康作息弹窗数量为{pushNum},总量为{pushAllNum},15分钟内关闭数为{close15MinNum},15分钟内关机成功率为{success15MinRate},30分钟内关闭数为{close30MinNum},30分钟内关机成功率为{success30MinRate}"
            print(logDetail)
            # 更新早间服务可见设备量
            updateSql = f"""
                update analysis_jkzx_push_rate set min_7hour_num= {min7hourNum}, new_num = {pushNum} ,cumulate_num = {pushAllNum},close_15min_num = {close15MinNum} ,close_30min_num = {close30MinNum} ,
                success_15min_rate = {success15MinRate},success_30min_rate = {success30MinRate} , update_time = now()  where
                    ref_date = '{date}' 
            """
            cur.execute(updateSql)
        saveLog(logDetail, date)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()


# 记录 数据分析-健康作息-服务推送成功率15分钟/30分钟 --  月度
def insertStartupRateMonth(toMonthDay):
    try:
        conn, cur = getDataConnection()
        #判断 analysis_jkzx_push_rate 表是否已经存在当天 数据
        countNum = selectNumBySql(f"select count(1) num from analysis_jkzx_push_rate t where 1=1  and t.ref_date =  '{toMonthDay}'")
        # 计算本月的新增弹窗数据量
        pushNum  = getSumNumByTableColumnNameAndDate('analysis_jkzx_push_rate', 'new_num', toMonthDay)
        # 获取所有健康作息 弹窗数量
        pushAllNum = selectNumBySql(
            f"select sum(new_num) from analysis_jkzx_push_rate t where 1=1 and LENGTH(t.ref_date) = 10  ")
        # 获取 本月 收到健康作息弹窗 15分钟内关机的设备量
        close15MinNum = getSumNumByTableColumnNameAndDate('analysis_jkzx_push_rate', 'close_15min_num', toMonthDay)
        # 获取 本月 收到健康作息弹窗 30分钟内关机的设备量
        close30MinNum = getSumNumByTableColumnNameAndDate('analysis_jkzx_push_rate', 'close_30min_num', toMonthDay)
        # 本月获取收到健康作息弹窗 15/30分钟关闭电视量及成功率
        success15MinRate = getRateByXY(close15MinNum, pushNum)
        success30MinRate = getRateByXY(close30MinNum, pushNum)

        if countNum == 0:
            logDetail = f"{toMonthDay}月新增-健康作息弹窗数量为{pushNum},总量为{pushAllNum},15分钟内关闭数为{close15MinNum},15分钟内关机成功率为{success15MinRate},30分钟内关闭数为{close30MinNum},30分钟内关机成功率为{success30MinRate}"
            print(logDetail)
            # 插入早间服务可见设备量
            insertSql = f"""insert into analysis_jkzx_push_rate(new_num,cumulate_num,close_15min_num,close_30min_num
            ,success_15min_rate,success_30min_rate,ref_date) 
                value({pushNum},{pushAllNum},{close15MinNum},{close30MinNum},{success15MinRate},{success30MinRate},'{toMonthDay}')"""
            cur.execute(insertSql)
        else:
            logDetail = f"{toMonthDay}月更新-健康作息弹窗数量为{pushNum},总量为{pushAllNum},15分钟内关闭数为{close15MinNum},15分钟内关机成功率为{success15MinRate},30分钟内关闭数为{close30MinNum},30分钟内关机成功率为{success30MinRate}"
            print(logDetail)
            # 更新早间服务可见设备量
            updateSql = f"""
                update analysis_jkzx_push_rate set new_num = {pushNum} ,cumulate_num = {pushAllNum},close_15min_num = {close15MinNum} ,close_30min_num = {close30MinNum} ,
                success_15min_rate = {success15MinRate},success_30min_rate = {success30MinRate} , update_time = now()  where
                    ref_date = '{toMonthDay}' 
            """
            cur.execute(updateSql)
        saveLog(logDetail, toMonthDay)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

# 获取当前日期
def todayYMD():
    today = datetime.datetime.now()-1
    # 获取想要的日期的时间
    re_date = (today).strftime('%Y-%m-%d')
    return re_date


# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m-%d')
    return re_date

# 获取前1天或N天的日期，beforeOfDay=1：前1天；beforeOfDay=N：前N天
def getMonthdate(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y-%m')
    return re_date

#如 2022年12月13号 获取 221213 作为分表后缀
def getdateyyMMdd(beforeOfDay):
    today = datetime.datetime.now()
    # 计算偏移量
    offset = datetime.timedelta(days=-beforeOfDay)
    # 获取想要的日期的时间
    re_date = (today + offset).strftime('%Y%m%d')
    re_date = re_date[2:]
    return re_date

def saveLog(detail,ref_date):
    try:
        conn, cur = getDataConnection()
        jobId = 31
        jobName = '核心指标-健康作息-推送成功率'
        tableName = 'analysis_jkzx_push_rate'
        # 插入日志表
        saveLogSql = """insert into log_xxljob_analysis (job_id,job_name,detail,table_name,ref_date) 
                value(%s,'%s','%s','%s','%s')""" % (jobId,jobName,detail,tableName,ref_date)
        cur.execute(saveLogSql)
        conn.commit()
    except Exception as e:
        print(e)
    finally:
        cur.close()
        conn.close()

if __name__ == '__main__':
    d = 1
    date = getdate(d)
    yyMMddDate = getdateyyMMdd(d)
    monthdate = getMonthdate(d)
    print (f"{date}日期,执行<数据分析-健康作息-服务推送成功率15分钟/30分钟>报表")
    insertStartupRate(date)
    insertStartupRateMonth(monthdate)
